<template>
  <u-input v-model="data" type="select" v-bind="attrs" @click="show = true" />
  <u-picker
    v-model="show"
    mode="time"
    :params="params"
    :default-time="
      data ? moment(data, format).format('YYYY-MM-DD HH:mm:ss') : currDate
    "
    @confirm="confirm"
  ></u-picker>
</template>
<script setup lang="ts">
import { useAttrs } from 'vue';
import { getDatePickerFormat } from '../config';
import moment from 'moment';

interface DatePicker<T> {
  year: T;
  month: T;
  day: T;
  hour: T;
  minute: T;
  second: T;
}

const attrs = useAttrs();
const props = defineProps<{
  modelValue: any;
  option: any;
}>();
const emits = defineEmits(['update:modelValue']);
const show = ref(false);
const data = ref();
const format = getDatePickerFormat(
  props.option.dateType,
  props.option.dateFormat
).label;

const params: DatePicker<boolean> = {
  year: format.includes('YYYY'),
  month: format.includes('MM'),
  day: format.includes('DD'),
  hour: format.includes('HH'),
  minute: format.includes('mm'),
  second: format.includes('ss'),
};
//获取格式化后的时间
const getPickData = (data: DatePicker<number>, getStr: boolean = false) => {
  let str = '';
  for (let key in params) {
    if (params[key]) {
      str += data[key];
    }
  }
  if (getStr) {
    return str;
  }
  return moment(str, format.replaceAll(/\.|\-|\/|[ ]|\:/g, '')).format(format);
};
const currDate = moment().format('YYYY-MM-DD HH:mm:ss');

watch(
  () => props.modelValue,
  (nVal) => {
    data.value = nVal;
  },
  {
    immediate: true,
  }
);

const confirm = (obj: any) => {
  emits('update:modelValue', getPickData(obj));
};
</script>
